<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class House extends Base
{
    //前置操作定义
    protected $beforeActionList = [
        'beforeIndex' =>  ['only'=>'index'],
        'beforeEdit'  =>  ['only'=>'edit'],
        'getPosition' =>  ['only'=>['edit','add']]
    ];
    private $mod;
    private $_data_mod;
    private $area;
    private $moudle;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('house');
        $this->_data_mod  = model('house_data');
        $this->list_field = 'id,area_name,title,img,rec_position,is_group,create_time,status,ordid';
        $this->sort       = 'ordid';
        $this->order      = 'asc,id desc';
        $this->moudle     = 'house';
        $this->assign('site',cache('site'));
    }
    public function beforeIndex(){
        $this->_data = [
            'addnews' => [
                'c' => 'Article',
                'a' => 'add',
                'str'    => '<a href="%s">添加动态</a>',
                'param' => ['house_id'=>'@id@','menuid'=>23],
                'isajax' => 0,
                'replace'=> ''
            ],
            'addpic' => [
                'c' => 'HousePic',
                'a' => 'add',
                'str'    => '<a href="%s">楼盘相册</a>',
                'param' => ['house_id'=>'@id@','menuid'=>465],
                'isajax' => 0,
                'replace'=> ''
            ],
            'addhuxing' => [
                'c' => 'HouseType',
                'a' => 'add',
                'str'    => '<a href="%s">添加户型</a>',
                'param' => ['house_id'=>'@id@','menuid'=>469],
                'isajax' => 0,
                'replace'=> ''
            ],
            'property' => [
                'c' => 'HouseProperty',
                'a' => 'index',
                'str'    => '<a href="%s">沙盘</a>',
                'param' => ['house_id'=>'@id@'],
                'isajax' => 0,
                'replace'=> ''
            ],
        ];
    }
    //搜索
    public function _search(){
        $map = array();
        $time_start = input('get.time_start');
        $time_end = input('get.time_end');
        if($time_start && !$time_end){
            $map['create_time'] = ['egt',strtotime($time_start)];
        }elseif($time_end && $time_end){
            $map['create_time'] = ['between',[strtotime($time_start),strtotime($time_end)+86399]];
        }
        ($keyword = input('get.keyword')) && $map['title'] = ['like', '%'.$keyword.'%'];
        $status = -1;
        if(isset($_GET['status']) && $_GET['status'] !== ''){
            $status = input('get.status/d');
        }
        $status>=0 && $map['status'] = ['eq',$status];
        $spid = '';
        $area         = input('get.area');
        if(strpos($area,',')!==FALSE){
            $area_arr    = explode(',',$area);
            $map['area'] = $area_arr[1];
            $spid        = str_replace(',','|',$area);
        }elseif(!empty($area)){
            $map['city'] = $area;
            $spid        = $area;
        }
        $this->assign('search', array(
            'time_start' => $time_start,
            'time_end' => $time_end,
            'selected_ids' => $spid,
            'status'  => $status,
            'keyword' => $keyword
        ));
        return $map;
    }
    public function addDo(){
        \app\common\model\House::event('before_insert',function($obj){
            $city = cache('city');
            if($obj->area){
                $area_arr  = explode(',',$obj->area);
                $map       = explode(',',input('post.map'));
                $obj->lat  = isset($map[1])?$map[1]:0;
                $obj->lng  = isset($map[0])?$map[0]:0;
                $obj->city = $area_arr[0];
                $obj->city_name = $city['cate'][$area_arr[0]]['name'];
                $obj->area      = isset($area_arr[1])?$area_arr[1]:0;
                $obj->area_name = isset($area_arr[1])?$city['cate'][$area_arr[1]]['name']:'';
                $obj->tags_id   = implode(',',$obj->tags_id);
                $obj->tags_name = $this->attrIdToname(5,input('post.tags_id/a'));
                $obj->house_status_name = $this->attrIdToname(1,$obj->house_status);
                $obj->room_type         = implode(',',$obj->room_type);
                $obj->room_type_name    = $this->attrIdToname(6,input('post.room_type/a'));
                $obj->house_type        = implode(',',$obj->house_type);
                $obj->house_type_name   = $this->attrIdToname(7,input('post.house_type/a'));
                $obj->floor_type        = implode(',',$obj->floor_type);
                $obj->floor_type_name   = $this->attrIdToname(8,input('post.floor_type/a'));
                $obj->zhuangxiu_name    = $this->attrIdToname(9,$obj->zhuangxiu_id);
            }

            if(!isset($_POST['position'])){
                $obj->rec_position = 0;
            }else{
                $obj->rec_position = 1;
            }
            return true;
        });
        \app\common\model\House::event('after_insert',function($obj){
            $data = input('post.data/a');
            if(isset($obj->is_group)){
               //todo 加入团购表中
                $info = isset($data['info'])?$data['info']:'';
                $this->addGroup($obj,$info);
            }
            if(empty($data['seo_title'])){
                $data['seo_title'] = $obj->title;
            }
            if(empty($data['seo_keys'])){
                $data['seo_keys'] = $this->setSeo(['title'=>$obj->title]);
            }
            $data['id'] = $obj->id;
            $this->_data_mod->save($data);
            $this->addPosition($obj->id);//添加推荐位
        });
        parent::addDo();
    }
    public function editDo(){
        \app\common\model\House::event('before_update',function($obj){
            $city = cache('city');
            if($obj->area){
                $area_arr  = explode(',',$obj->area);
                $map       = explode(',',input('post.map'));
                $obj->lat  = isset($map[1])?$map[1]:0;
                $obj->lng  = isset($map[0])?$map[0]:0;
                $obj->city = $area_arr[0];
                $obj->city_name = $city['cate'][$area_arr[0]]['name'];
                $obj->area      = isset($area_arr[1])?$area_arr[1]:0;
                $obj->area_name = isset($area_arr[1])?$city['cate'][$area_arr[1]]['name']:'';
                $obj->tags_id   = implode(',',$obj->tags_id);
                $obj->tags_name = $this->attrIdToname(5,input('post.tags_id/a'));
                $obj->house_status_name = $this->attrIdToname(1,$obj->house_status);
                $obj->room_type         = implode(',',$obj->room_type);
                $obj->room_type_name    = $this->attrIdToname(6,input('post.room_type/a'));
                $obj->house_type        = implode(',',$obj->house_type);
                $obj->house_type_name   = $this->attrIdToname(7,input('post.house_type/a'));
                $obj->floor_type        = implode(',',$obj->floor_type);
                $obj->floor_type_name   = $this->attrIdToname(8,input('post.floor_type/a'));
                $obj->zhuangxiu_name    = $this->attrIdToname(9,$obj->zhuangxiu_id);
            }
            if(!isset($_POST['position'])){
                $obj->rec_position = 0;
            }else{
                $obj->rec_position = 1;
            }
            return true;
        });
        \app\common\model\House::event('after_update',function($obj){
            $data = input('post.data/a');
            if(isset($obj->is_group)){
                //todo 更新团购表数据
                if(model('house_group')->where(['house_id'=>$obj->id])->count()==0){
                    //新增
                    $info = isset($data['info'])?$data['info']:'';
                    $this->addGroup($obj,$info);
                }else{
                    //更新
                    $group['youhui'] = $obj->group_youhui;
                    model('house_group')->save($group,['house_id'=>$obj->id]);
                }
            }else{
                model('house_group')->where(['house_id'=>$obj->id])->delete();
            }
            $data['id'] = $obj->id;
            $this->_data_mod->save($data,['id'=>$obj->id]);
            $this->addPosition($obj->id);//添加、修改推荐位
        });
        parent::editDo();
    }
    public function delete(){
        //删除后置操作
        \app\common\model\House::event('after_delete',function($obj){
            $where['house_id'] = $obj->id;
            //删除楼盘扩展数据
            model('house_data')->where(['id'=>$obj->id])->delete();
            //删除团购数据
            model('house_group')->where($where)->delete();
            //删除楼盘相册数据
            model('house_pic')->where($where)->delete();
            //删除楼盘户型数据
            model('house_type')->where($where)->delete();
            //删除楼盘楼栋数据
            model('house_property')->where($where)->delete();
            //删除楼盘沙盘数据
            model('house_property_pic')->where($where)->delete();
            //删除楼盘价格数据
            model('house_price')->where($where)->delete();
            //删除推荐楼盘数据
            action('Position/deleteByHouseId',['house_id'=>$obj->id],'controller');
        });
        parent::delete();
    }
    //添加团购
    private function addGroup($obj,$info){
        $group['house_id']    = $obj->id;
        $group['title']       = $obj->title;
        $group['house_title'] = $obj->title;
        $group['city']        = $obj->city;
        $group['area']        = $obj->area;
        $group['youhui']      = isset($obj->group_youhui)?$obj->group_youhui:'';
        $group['price']       = $obj->average_price;
        $group['old_price']   = $obj->average_price;
        $group['begin_time']  = time();
        $group['end_time']    = $group['begin_time'] + 86400*30;
        $group['img']         = isset($obj->img)?$obj->img:'';
        $group['info']        = $info;
        model('house_group')->save($group);
    }
    /**
     * 获取推荐位
     */
    public function getPosition(){
        $where['model'] = $this->moudle;
        $pos_list = model('position_cate')->where($where)->field('id,title')->select();
        $this->assign('pos_list',$pos_list);
    }
    //把楼盘添加到推荐位中
    private function addPosition($id){
        $position   = input('post.position/a');//新选择的推荐位id
        $exists_pos = input('post.exists_pos');//原推荐位id
        $exists_pos_arr = [];
        $exists_pos && $exists_pos_arr = explode(',',$exists_pos);
        $add = [];$del  = [];
        if($position && $exists_pos_arr){
            foreach($position as $v){
                if(!in_array($v,$exists_pos_arr)){
                    //新增
                    $add[] = $v;
                }
            }
            foreach($exists_pos_arr as $v){
                if(!in_array($v,$position)){
                    //删除
                    $del[] = $v;
                }
            }
        }elseif($position && !$exists_pos){
            $add = $position;
        }elseif(!$position && $exists_pos){
            $del = $exists_pos_arr;
        }
        if($del){
            model('position')->where(['house_id'=>$id,'model'=>$this->moudle,'cate_id'=>['in',$del]])->delete();
            model('position_cate')->where(['id'=>['in',$del],'num'=>['gt',0]])->setDec('num');
        }
        if($add){
            action('Position/addPosition',['model'=>$this->moudle,'ids'=>$id,'cate_id'=>$add],'controller');//添加推荐位
        }

    }
    //编辑前置操作
    public function beforeEdit(){
        $id = input('param.id/d',0);
        if($id){
            $detail = $this->_data_mod->where(['id'=>$id])->find();
            $pos_id = model('position')->where(['house_id'=>$id,'model'=>$this->moudle])->column('cate_id');//获取该楼盘 所属的推荐位id
            $this->assign('detail',$detail);
            $this->assign('pos_id',$pos_id);
        }else{
            $this->error('参数错误');
        }
    }
    /**
     * 异步检查楼盘是否存在
     */
    public function ajaxCheckTitle(){
        $title = input('get.J_title');
        $id    = input('param.id/d',0);
        $return['status'] = 1;
        $where['title'] = $title;
        $id && $where['id'] = ['neq',$id];
        $count = $this->mod->where($where)->count();
        if($count > 0){
            $return['status'] = 0;
        }
        return json($return);
    }
    /**
     * @param $mid
     * @param $id
     * @return array|string
     * 属性名转换成名称
     */
    private function attrIdToname($mid,$id){
        $attr = cache('linkmenu_'.$mid);
        $attr = $attr['cate'];
        $data = [];
        if(is_array($id)){
            foreach($id as $v){
                $data[] = $attr[$v]['name'];
            }
        }elseif(is_numeric($id)){
            $data = $attr[$id]['name'];
        }else{
            $data = '';
        }
        return $data;
    }
    //关键词设置
    private function setSeo($data){
        $seo_keys = "title,title价格,title怎么样,title售楼处地址,title售楼处电话,title优惠";
        $seo_keys = str_replace('title',$data['title'],$seo_keys);
        return $seo_keys;
    }
    /**
     * 选择内容
     */
    public function publicSelectContent(){
        $model = input('param.model','house');
        $type  = input('param.type','radio');//选择框类型radio checkbox
        $city  = input('param.cate/d',0);
        $keyword  = input('param.keyword');
        $pagesize = 24;
        $mod      =  model($model);
        $map['status']            = 1;
        $city && $map['city']     = $city;
        $keyword && $map['title'] = ['like','%'.$keyword.'%'];
        $total     = $mod->where($map)->count();
        $totalPage = ceil($total/$pagesize);
        $this->assign('model',$model);
        $this->assign('city',$city);
        $this->assign('type',$type);
        $this->assign('totalPage',$totalPage);
        $this->ajaxReturn(1,'',$this->fetch());
    }

    /**
     * ajax获取内容
     */
    public function ajaxGetList(){
        $lists = $this->getContent();
        if($lists){
            $this->ajaxReturn(1,'',$lists);
        }else{
            $this->ajaxReturn(0,'无相关数据');
        }
    }
    private function getContent(){
        $pagesize = 24;
        $page     = input('param.page/d',1);
        $keyword  = input('param.keyword');
        $model    = input('param.model','house');
        $city     = input('param.city/d',0);
        $map['status'] = 1;
        if($keyword){
            $map['title'] = ['like','%'.$keyword.'%'];
        }
        $field = 'id,title,img';
        if($model == 'house'){
            $field .= ',average_price';
        }else{
            $field .= ',price';
        }
        $city && $map['city'] = $city;
        $lists = model($model)->where($map)->field($field)->page($page,$pagesize)->select();
        return $lists;
    }
}